from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from starlette.requests import Request

from app.core.config import settings

# Use remote address as the key function
limiter = Limiter(key_func=get_remote_address, default_limits=["1000/hour", "100/minute"])

# You can define specific limits here or apply them directly in routers
# Example specific limit:
# limiter.limit("5/minute")(your_endpoint_function)

def get_limiter():
    return limiter

# This function can be used if you want to key limits based on the logged-in user
# It requires the get_current_user dependency to have run successfully first.
# Ensure endpoints using this are protected by authentication.
async def get_current_user_identifier(request: Request) -> str:
    if hasattr(request.state, 'current_user') and request.state.current_user:
        # Assuming current_user object has an identifier like 'id' or 'username'
        return str(request.state.current_user.id) 
    else:
        # Fallback to IP address if user is not available (e.g., for optional auth routes)
        # Or raise an error if user MUST be present for the limit
        # raise Exception("User not found in request state for rate limiting")
        return get_remote_address(request)

# Limiter instance specifically for user-based limits
user_limiter = Limiter(key_func=get_current_user_identifier)

# Middleware and exception handler setup will typically happen in main.py
